package com.woniuxy.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.woniuxy.entity.Log;
import com.woniuxy.entity.PowerUser;
import com.woniuxy.entity.dto.LogDTO;
import com.woniuxy.mapper.LogMapper;
import com.woniuxy.mapper.PowerUserMapper;
import com.woniuxy.service.LogService;
import com.woniuxy.service.PowerUserService;
import com.woniuxy.util.PageData;
import com.woniuxy.util.ResponseData;
import com.woniuxy.util.UserContext;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.List;

/**
 * @program: tsm
 * @description:
 * @create: 2024-10-23 17:15
 **/
@Service
public class LogServiceImpl implements LogService {
    @Resource
    private LogMapper logMapper;
    @Resource
    private PowerUserMapper powerUserMapper;

    @Override
    public ResponseData<?> queryLog(PageData<LogDTO> pageData) {
        PageHelper.startPage(pageData.getPageNum(), pageData.getPageSize());
        List<LogDTO> logDTOS = logMapper.queryLog(pageData.getParam());
        PageInfo pageInfo = new PageInfo(logDTOS);
        return new ResponseData<>().ok(pageInfo);
    }

    @Override
    public void op(long time, String className, String methodName) {
        Long userId = UserContext.getUserId();
        PowerUser powerUser = powerUserMapper.queryPowerUserById(userId.intValue());


        if (time>0){
            Log logClass = logMapper.queryByClassName(className);
            Log logMethod = logMapper.queryByMethodName(methodName);

            if (logClass!=null&&logMethod!=null){
                logMapper.update(logClass);
                logMapper.update(logMethod);
            }else {
                Log log = new Log();
                log.setClassName(className);
                log.setMethodName(methodName);
                //获取username放入
                log.setOperator(powerUser.getUsername());
                // 设置起始时间为当前时间
                LocalDateTime startTime = LocalDateTime.now();
                log.setOperationTime(startTime.toString());

                // 计算结束时间：起始时间加上传过来的运行时间
                // 将毫秒转换为纳秒,因为localDateTIme方法没有毫秒单位的操作需要转换一下
                LocalDateTime endTime = startTime.plusNanos(time * 1_000_000);

                log.setEndTime(endTime.toString());


                logMapper.add(log);
            }
        }
    }

    @Override
    public ResponseData<?> queryByMethodName(String name) {
        return new ResponseData<>().ok(logMapper.queryByMethodName(name));
    }

    @Override
    public ResponseData<?> queryByClassName(String name) {
        return new ResponseData<>().ok(logMapper.queryByClassName(name));
    }

    @Override
    public ResponseData<?> batchDelete() {
        return new ResponseData<>().ok(logMapper.batchDelete());
    }
}
